package com.findviewbydream.evil.eda;


import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.RequiresApi;
import android.support.design.widget.Snackbar;
import android.support.v4.view.PagerAdapter;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.findviewbydream.evil.eda.Activity.BaseActivity;
import com.findviewbydream.evil.eda.Activity.WebActivity;
import com.findviewbydream.evil.eda.Answer.ItemListActivity;
import com.findviewbydream.evil.eda.Bean.LoopViewPagerBean;
import com.findviewbydream.evil.eda.Data.Data;
import com.findviewbydream.evil.eda.Data.UserData;
import com.findviewbydream.evil.eda.EventBus.CloseLeftEvent;
import com.findviewbydream.evil.eda.Fragment.Menu.LeftMenu;
import com.findviewbydream.evil.eda.Utils.Dialog.CustomMaterialDialog;
import com.findviewbydream.evil.eda.Utils.SuperToast.ProgressToast;
import com.findviewbydream.evil.eda.Utils.SuperToast.SuperToast;
import com.findviewbydream.evil.eda.Utils.Utils;
import com.findviewbydream.evil.eda.View.Dialog.MessageDialog;
import com.findviewbydream.evil.eda.View.superindicatorlibray.CircleIndicator;
import com.findviewbydream.evil.eda.View.superindicatorlibray.LoopViewPager;
import com.github.ksoichiro.android.observablescrollview.ObservableScrollView;
import com.github.ybq.android.spinkit.SpinKitView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sunfusheng.marqueeview.MarqueeView;
import com.wooplr.spotlight.SpotlightView;
import com.wooplr.spotlight.utils.SpotlightListener;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

import okhttp3.Call;

import static com.findviewbydream.evil.eda.R.id.recyclerView;

public class MainActivity extends BaseMainActivity
{
    private FragmentManager fragmentManager;
    private FragmentTransaction fragmentTransaction;
    private FrameLayout container_left;

    private DrawerLayout drawerLayout;
    private ObservableScrollView observableScrollView;
    private CircleIndicator indicator;
    private LoopViewPager loopViewPager;
    private MarqueeView marqueeView;
    private CardView card_10;
    private CardView card_20;
    private CardView card_50;
    private CardView card_all;

    private CustomMaterialDialog dialog;

    private ArrayList<LoopViewPagerBean> loopViewPagerBeanArrayList;

    /*用于继承*/
    protected void setList()
    {

    }

    @Override
    public int setContentView()
    {
        return R.layout.activity_main;
    }

    @Override
    public void onCreate()
    {
        initView();/*初始化控件*/
        initLeftMenu();/*初始化左侧菜单*/

        /*判断是后是第一次登陆*/
        SharedPreferences preferences = Utils.getSharedPreference();
        if (preferences.getBoolean("first", false))
            showMessageDialog();/*推送消息*/
        else
        {
            SharedPreferences.Editor editor = preferences.edit();
            editor.putBoolean("first", true);
            editor.apply();
        }


        setList();/*设置首页列表*/

    /*    setIndicator();*//*首页图片轮询*//*
        setAd();*//*设置中间广告*//*

        onClick();*//*跳转到答题列表的点击事件*/
        setGuilde();/*新手引导*/
    }

    /**
     * 初始化控件
     */
    private void initView()
    {
        container_left = (FrameLayout) findViewById(R.id.container_left);
        drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
        /*indicator = (CircleIndicator) findViewById(R.id.indicator);
        loopViewPager = (LoopViewPager) findViewById(R.id.loopViewPager);
        observableScrollView = (ObservableScrollView) findViewById(R.id.observableScrollView);
        marqueeView = (MarqueeView) findViewById(R.id.marqueeView);
        card_10 = (CardView) findViewById(R.id.card_10);
        card_20 = (CardView) findViewById(R.id.card_20);
        card_50 = (CardView) findViewById(R.id.card_50);
        card_all = (CardView) findViewById(R.id.card_all);*/
    }

    /**
     * 初始化左侧菜单
     */
    private void initLeftMenu()
    {
        fragmentManager = getFragmentManager();
        fragmentTransaction = fragmentManager.beginTransaction();

        if (fragmentManager.findFragmentById(R.id.container_left) == null)
            fragmentTransaction.add(R.id.container_left, LeftMenu.newInstance());

        fragmentTransaction.commit();
    }


    /**
     * 推送消息
     */
    private void showMessageDialog()
    {
        String msgNum;/*信息的序列号，通过序列号辨识此条信息用户是否已读*/
        final SharedPreferences preferences = Utils.getSharedPreference();

        msgNum = preferences.getString("msgNum", "0");

        OkHttpUtils.post().url(Data.IP + "SendMessageServlet")
                .addParams("phone", UserData.getUserPhoneNum())
                .addParams("imei", UserData.getUserIMEI())
                .addParams("msgNum", msgNum)
                .build().execute(new StringCallback()
        {
            @Override
            public void onError(Call call, Exception e, int id)
            {
            }

            @Override
            public void onResponse(String response, int id)
            {
                if (response.indexOf(Data.BREAKSTRING) > 0)
                {
                    String[] ss = response.split(Data.BREAKSTRING);
                    String msgNum = ss[0];
                    String msg = ss[1];

                    SharedPreferences.Editor editor = preferences.edit();
                    editor.putString("msgNum", msgNum);
                    editor.apply();

                    MessageDialog.showDialog(MainActivity.this, msg);
                }
                else if (!response.equals("null"))
                {
                    MessageDialog.showDialog(MainActivity.this, response);
                }
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(CloseLeftEvent event)
    {
        if (drawerLayout.isDrawerOpen(container_left))
            new Handler().postDelayed(() -> drawerLayout.closeDrawer(container_left), 1000);
    }

    @Override
    protected void onStart()
    {
        super.onStart();

        EventBus.getDefault().register(this);

        /*if (loopViewPager != null)
            loopViewPager.setLooperPic(true);*/
    }

    @Override
    protected void onStop()
    {
        super.onStop();

        EventBus.getDefault().unregister(this);

      /*  if (loopViewPager != null)
            loopViewPager.setLooperPic(false);*/
    }
/*

    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        loopViewPager.setLooperPic(false);
        loopViewPager.clearOnPageChangeListeners();
        loopViewPager = null;
    }
*/

    @Override
    public void onBackPressed()
    {
        //super.onBackPressed();
        if (drawerLayout.isDrawerOpen(container_left))
            drawerLayout.closeDrawer(container_left);
        else
        //twoClickExit();
        {
            showDialog();
        }
    }

    /*********************************************
     * 新手引导
     */
    private void setGuilde()
    {
        new SpotlightView.Builder(this)
                .introAnimationDuration(400)
                .enableRevalAnimation(true)
                .performClick(true)
                .fadeinTextDuration(400)
                .headingTvColor(Utils.getColor(R.color.p_blue_light))
                .headingTvSize(32)
                .headingTvText("答题")
                .subHeadingTvColor(Color.parseColor("#ffffff"))
                .subHeadingTvSize(16)
                .subHeadingTvText("点击这里，进入答题列表\n如果回答正确，将会有流量赠送（次日/月）！")
                .maskColor(Color.parseColor("#dc000000"))
                .target(findViewById(R.id.toolbar))
                .lineAnimDuration(400)
                .lineAndArcColor(Utils.getColor(R.color.p_blue_light))
                .dismissOnTouch(true)
                .dismissOnBackPress(true)
                .enableDismissAfterShown(true)
                .usageId("card") //UNIQUE ID
                .setListener(s -> {
                            drawerLayout.openDrawer(container_left);
                            new Handler().postDelayed(() ->
                                    new SpotlightView.Builder(this)
                                            .introAnimationDuration(400)
                                            .enableRevalAnimation(true)
                                            .performClick(true)
                                            .fadeinTextDuration(400)
                                            .headingTvColor(Utils.getColor(R.color.p_lime))
                                            .headingTvSize(32)
                                            .headingTvText("列表")
                                            .subHeadingTvColor(Color.parseColor("#ffffff"))
                                            .subHeadingTvSize(16)
                                            .subHeadingTvText("点击左上角菜单键\n或者从屏幕左侧向右划动\n都可以开启列表，查看更多功能！")
                                            .maskColor(Color.parseColor("#dc000000"))
                                            .target(findViewById(R.id.userImg))
                                            .lineAnimDuration(400)
                                            .lineAndArcColor(Utils.getColor(R.color.p_lime))
                                            .dismissOnTouch(true)
                                            .dismissOnBackPress(true)
                                            .enableDismissAfterShown(true)
                                            .usageId("userImg") //UNIQUE ID
                                            .show(), 500);
                        }
                )
                .show();
    }

    /*********************************************
     * 双击退出
     */
    private long exitTime = 0;
    private ProgressToast progressToast;
    private int progress;

    private void twoClickExit()
    {
        if ((System.currentTimeMillis() - exitTime) > 2000)
        {
            progressToast = SuperToast.progressToast(MainActivity.this)
                    .setText("再次点击退出")
                    .setBackgroundColor(ProgressToast.Background.GRAY)
                    .setAnimations(ProgressToast.Animations.POPUP)
                    .setMaxProgress(200).show();
            new Utils.SHandler()
            {
                @Override
                public void thread(Handler handler)
                {
                    for (progress = 1; progress <= 200; progress++)
                    {
                        handler.sendEmptyMessage(0);
                        Utils.Threadsleep(10);
                    }
                }

                @Override
                public void handler()
                {
                    progressToast.setProgress(progress);
                }
            }.startByCustom();
            exitTime = System.currentTimeMillis();
        }
        else
        {
            dialog.dismiss();
            finish();
        }
    }

    /**
     * 提示反馈信息的dialog
     */
    private void showDialog()
    {
        dialog = new CustomMaterialDialog(this);
        View view = View.inflate(this, R.layout.feedback_dialog, null);

        dialog.setContentView(view).show();

        final EditText editText = (EditText) view.findViewById(R.id.editText);
        final SpinKitView loading = (SpinKitView) view.findViewById(R.id.loading);
        TextView cancel = (TextView) view.findViewById(R.id.cancel);
        TextView submit = (TextView) view.findViewById(R.id.submit);
        TextView exit = (TextView) view.findViewById(R.id.exit);

        cancel.setOnClickListener(view1 -> dialog.dismiss());

        exit.setOnClickListener(view12 -> {
            dialog.dismiss();
            new Handler().postDelayed(this::finish, 500);
        });

        submit.setOnClickListener(view13 -> {
            if (editText.getText().length() == 0)
                Snackbar.make(findViewById(R.id.drawerLayout), "请勿回复空内容！", Snackbar.LENGTH_SHORT).show();
            else
            {
                loading.setVisibility(View.VISIBLE);
                OkHttpUtils.post().url(Data.IP + "FeedbackServlet")
                        .addParams("type", "app")
                        .addParams("phone", UserData.getUserPhoneNum())
                        .addParams("imei", UserData.getUserIMEI())
                        .addParams("feedbackInformation", editText.getText().toString())
                        .build()
                        .execute(new StringCallback()
                        {
                            @Override
                            public void onError(Call call, Exception e, int id)
                            {
                                loading.setVisibility(View.GONE);
                                Snackbar.make(findViewById(R.id.drawerLayout), "提交失败！", Snackbar.LENGTH_SHORT).show();
                            }

                            @Override
                            public void onResponse(String response, int id)
                            {
                                loading.setVisibility(View.GONE);
                                dialog.dismiss();
                                new Handler().postDelayed(MainActivity.this::finish, 300);
                            }
                        });
            }
        });

    }
}
  /*  *//**
 * 设置轮播
 * <p>
 * 首页轮播适配器
 * <p>
 * 设置滚动广告
 * <p>
 * 跳转到答题
 * <p>
 * 首页轮播适配器
 * <p>
 * 设置滚动广告
 * <p>
 * 跳转到答题
 * <p>
 * 首页轮播适配器
 * <p>
 * 设置滚动广告
 * <p>
 * 跳转到答题
 * <p>
 * 首页轮播适配器
 * <p>
 * 设置滚动广告
 * <p>
 * 跳转到答题
 * <p>
 * 首页轮播适配器
 * <p>
 * 设置滚动广告
 * <p>
 * 跳转到答题
 * <p>
 * 首页轮播适配器
 * <p>
 * 设置滚动广告
 * <p>
 * 跳转到答题
 * <p>
 * 首页轮播适配器
 * <p>
 * 设置滚动广告
 * <p>
 * 跳转到答题
 * <p>
 * 首页轮播适配器
 * <p>
 * 设置滚动广告
 * <p>
 * 跳转到答题
 * <p>
 * 首页轮播适配器
 * <p>
 * 设置滚动广告
 * <p>
 * 跳转到答题
 * <p>
 * 首页轮播适配器
 * <p>
 * 设置滚动广告
 * <p>
 * 跳转到答题
 * <p>
 * 首页轮播适配器
 * <p>
 * 设置滚动广告
 * <p>
 * 跳转到答题
 * <p>
 * 首页轮播适配器
 * <p>
 * 设置滚动广告
 * <p>
 * 跳转到答题
 * <p>
 * 首页轮播适配器
 * <p>
 * 设置滚动广告
 * <p>
 * 跳转到答题
 * <p>
 * 首页轮播适配器
 * <p>
 * 设置滚动广告
 * <p>
 * 跳转到答题
 *//*
    private void setIndicator()
    {
        loopViewPager.setLooperPic(false);
        OkHttpUtils.post().url(Data.IP + "LoopViewPagerServlet")
                .addParams("phone", UserData.getUserPhoneNum())
                .addParams("imei", UserData.getUserIMEI())
                .build()
                .execute(new StringCallback()
                {
                    CustomMaterialDialog dialog;

                    @Override
                    public void onError(Call call, Exception e, int id)
                    {
                        dialog = new CustomMaterialDialog(MainActivity.this)
                                .setMessage("首页获取失败，是否重试？")
                                .setButtonText("退出", "重试")
                                .setButtonOnClick(() -> {
                                            dialog.dismiss();
                                            new Handler().postDelayed(() -> finish(), 500);
                                        }
                                        , () -> {
                                            dialog.dismiss();
                                            setIndicator();
                                        });
                        dialog.show();
                    }

                    @Override
                    public void onResponse(String response, int id)
                    {
                        Utils.Log("获取成功" + response);
                        *//*解析json*//*
                        {
                            loopViewPagerBeanArrayList = new Gson().fromJson(response
                                    , new TypeToken<ArrayList<LoopViewPagerBean>>()
                                    {
                                    }.getType());
                        }
                        *//*设置轮询*//*
                        {
                            CustomPagerAdapter pagerAdapter = new CustomPagerAdapter();
                            loopViewPager.setAdapter(pagerAdapter);
                            loopViewPager.setScrollable(true);
                            loopViewPager.setLooperPic(true);//是否设置自动轮播
                            indicator.setViewPager(loopViewPager);
                        }
                    }
                });
    }

    *//**
 * 首页轮播适配器
 *//*
    private class CustomPagerAdapter extends PagerAdapter
    {
        private ImageView imageView;
        private TextView image_desc;

        @Override
        public int getCount()
        {
            return loopViewPagerBeanArrayList.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object)
        {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, final int position)
        {
            final LoopViewPagerBean bean = loopViewPagerBeanArrayList.get(position);
            View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.loopviewpager_item, container, false);
            initView(view);
            Glide.with(MainActivity.this).load(Utils.getNetImg(bean.getImgRes())).placeholder(R.drawable.loading).into(imageView);
            image_desc.setText(bean.getDesc());
            container.addView(view);

            view.setOnClickListener(view1 ->
                    startActivity(
                            new Intent(MainActivity.this, WebActivity.class)
                                    .putExtra(WebActivity.TITLE, bean.getDesc())
                                    .putExtra(WebActivity.URL, bean.getUrl())));

            return view;
        }

        private void initView(View view)
        {
            imageView = (ImageView) view.findViewById(R.id.imageView);
            image_desc = (TextView) view.findViewById(R.id.image_desc);
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object)
        {
            container.removeView((View) object);
        }
    }

    *//**
 * 设置滚动广告
 *//*
    private void setAd()
    {
        String ad = "由于题库目前题目数量不足,20M流量区和50M流量区暂时为空,请您谅解!";
        marqueeView.startWithText(ad);
    }

    *//**
 * 跳转到答题
 *//*
    private void onClick()
    {
        card_10.setOnClickListener(view ->
                startActivity(new Intent(MainActivity.this, ItemListActivity.class)
                        .putExtra("title", "10M流量答题列表")
                        .putExtra(ItemListActivity.FLOW_TYPE, "10")));
        card_20.setOnClickListener(view ->
                startActivity(new Intent(MainActivity.this, ItemListActivity.class)
                        .putExtra("title", "20M流量答题列表")
                        .putExtra(ItemListActivity.FLOW_TYPE, "20")));
        card_50.setOnClickListener(view ->
                startActivity(new Intent(MainActivity.this, ItemListActivity.class)
                        .putExtra("title", "50M流量答题列表")
                        .putExtra(ItemListActivity.FLOW_TYPE, "50")));
        card_all.setOnClickListener(view ->
                startActivity(new Intent(MainActivity.this, ItemListActivity.class)
                        .putExtra("title", "全部类型流量答题列表")
                        .putExtra(ItemListActivity.FLOW_TYPE, "ALL")));
    }
*/